<?php
// 程序版本的升级

namespace PKApp\Install;

use PKApp\Install\Classes\InstallController;
use PKApp\Install\Classes\InstallService;
use PKFrame\DataHandler\Numbers;
use PKFrame\Extend\Zip;

/**
 * Class Upgrade
 * @package PKApp\Install
 *
 * 版本号的比较，是否存在版本差异
 * 将当前的低版本从云端获取与新版本之间存在的版本跨度
 * 云端从库获取最新版与请求版本之间存在的版本跨度
 *  云端将版本跨度之间的变化的结构整理打包
 *  云端通知下载包
 *
 */
class Upgrade extends InstallController
{

    protected $version_now, $version_new;
    protected $path_zip, $path_sql;

    public function __construct()
    {
        $this->version_new = loader(PATH_PK . VERSION_FILE, true);
        $this->version_now = Numbers::To(loader(PATH_CACHE . VERSION_FILE, true));
        $this->path_zip = 'UpgradeByZip';
        $this->path_sql = 'UpgradeBySQL';
        if ($this->version_now == $this->version_new) {
            header('location:/admin.php');
        }
    }

    public function Main()
    {
        fileHelper()->RemoveDir(PATH_TMP . $this->path_zip);
        fileHelper()->RemoveDir(PATH_TMP . $this->path_sql);
        $this->assign([
            'version_now' => $this->version_now,
            'version_new' => $this->version_new,
        ])->fetch();
    }

    public function Done()
    {
        fileHelper()->UnLink(PATH_CACHE . VERSION_FILE);
        fileHelper()->Copy(PATH_PK . VERSION_FILE, PATH_CACHE, VERSION_FILE);
        $this->json();
    }

    public function Change()
    {
        $file_path = urldecode(request()->post('file_path'));
        if (file_exists($file_path)) {
            $service = new InstallService();
            $service->Upgrade($file_path);
        }
        $this->json();
    }

    public function GetChangeFile()
    {
        $version_range = $this->version_now . '-' . $this->version_new;
        $list_file = fileHelper()->OpenFolder(
            PATH_TMP . $this->path_sql . DS . $version_range, 'sql'
        );
        $this->json($list_file, count($list_file));
    }

    public function ReleaseZip()
    {
        $version_range = $this->version_now . '-' . $this->version_new;
        $zip = new Zip();
        $this->json($zip->unZip(
            PATH_TMP . $this->path_zip . DS . $version_range . '.zip',
            PATH_TMP . $this->path_sql . DS . $version_range
        ));
    }

    public function DownLoad()
    {
        $file = $this->version_now . '-' . $this->version_new . '.zip';
        $path = PATH_TMP . $this->path_zip . DS;
        !file_exists($path . $file) ?: fileHelper()->UnLink($path . $file);
        fileHelper()->DownLoadOnlineToLocal($path, $file,
            SERVICE_DOMAIN . 'UpgradeByZip/' . $file);
        $this->json();
    }
}